package handler

import (
	"center-data-platform/app/content/model"
	esmodel "center-data-platform/utils/elasticsearch/model"
	"center-data-platform/utils/queue/internal/svc"
	"context"
	"encoding/json"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"strings"
)

type KqPostHandler struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewKqPostHandler(ctx context.Context, svcCtx *svc.ServiceContext) *KqPostHandler {
	return &KqPostHandler{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *KqPostHandler) Consume(ctx context.Context, key, val string) error {
	//client := elasticsearch.NewClient()
	var content model.Content
	err := json.Unmarshal([]byte(val), &content)
	if err != nil {
		return err
	}
	post := esmodel.Post{
		Id:          content.Id,
		UserId:      content.UserId,
		Type:        content.Type,
		Title:       content.Title,
		Content:     content.Content,
		Cover:       content.Cover,
		FileIds:     strings.Split(content.FileIds, ","),
		Description: content.Description,
		Tags:        strings.Split(content.Tags, ","),
		CreatedTime: content.CreatedTime.Format("2006-01-02 15:04:05"),
		UpdatedTime: content.UpdatedTime.Format("2006-01-02 15:04:05"),
		Status:      content.Status,
	}
	newVal, err := json.Marshal(post)
	if err != nil {
		return err
	}
	res, err := l.svcCtx.ElasticSearch.CreateDoc("post", string(newVal))
	if err != nil {
		return err
	}
	if res.StatusCode < 300 {
		return nil
	}
	logx.Infof("es response : %v ", res)
	return errors.New("作品存储es失败")
}
